<template>
  <div class="post-detail" v-loading="loading">
    <div class="post-card" v-if="post">
      <div class="post-header">
        <h2 class="title">{{ post.title }}</h2>
        <div class="meta">{{ post.userName }} · {{ formatTime(post.createdAt) }} · {{ post.postType }}</div>
      </div>
      <div class="content" v-html="escapeHtml(post.content).replace(/\n/g,'<br/>')"></div>
      <div class="actions">
        <el-button size="small" @click="likePost">
          <el-icon><StarFilled /></el-icon>
          {{ post.likeCount }}
        </el-button>
        <el-tag v-if="post.isSolved" type="success" size="large" effect="dark">
          <el-icon><Check /></el-icon>
          问题已解决
        </el-tag>
        <el-tag v-else type="warning" size="large" effect="plain">
          <el-icon><QuestionFilled /></el-icon>
          待解决
        </el-tag>
        <div style="flex:1"></div>
        <el-button v-if="isOwner" size="small" @click="openEdit">
          <el-icon><Edit /></el-icon>
          编辑
        </el-button>

        <el-button v-if="isOwner" size="small" type="danger" @click="removePost">
          <el-icon><Delete /></el-icon>
          删除
        </el-button>
      </div>
    </div>

    <div class="comments-card">
      <div class="comments-header">
        <h3>全部评论（{{ total }}）</h3>
      </div>

      <div class="comment-editor">
        <el-input v-model="commentText" type="textarea" :rows="4" placeholder="写下你的回复..." />
        <div style="text-align:right; margin-top:8px;">
          <el-button type="primary" @click="submitComment" :loading="commenting">发表评论</el-button>
        </div>
      </div>

      <el-empty v-if="items.length === 0 && !loading" description="暂无评论" />

      <div v-else class="comment-list">
        <!-- 已采纳的答案优先显示 -->
        <div v-for="c in sortedComments" :key="c.id" class="comment-item" :class="{ 'best-answer': c.isSolution }">
          <div class="comment-header">
            <div class="comment-meta">
              {{ c.userName }} · {{ formatTime(c.createdAt) }}
            </div>
            <el-tag v-if="c.isSolution" type="success" size="small" effect="dark">
              <el-icon><Medal /></el-icon>
              最佳答案
            </el-tag>
          </div>
          <div class="comment-content" v-html="escapeHtml(c.content).replace(/\n/g,'<br/>')"></div>
          <div class="comment-actions">
            <el-button size="small" @click="likeComment(c.id)">
              <el-icon><Check /></el-icon>
              {{ c.likeCount }}
            </el-button>
            
            <el-button 
              size="small" 
              type="success" 
              @click="markSolution(c.id)"
            >
              <el-icon><Select /></el-icon>
              采纳
            </el-button>
            

            

            

          </div>
        </div>
      </div>

      <div class="pager">
        <el-pagination
          v-model:current-page="page"
          v-model:page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next"
          @current-change="loadComments"
        />
      </div>
    </div>
  </div>

  <!-- 编辑帖子 -->
  <el-dialog v-model="showEdit" title="编辑帖子" width="700px" :close-on-click-modal="false">
    <el-form :model="editForm" label-width="80px">
      <el-form-item label="标题">
        <el-input v-model="editForm.title" />
      </el-form-item>
      <el-form-item label="内容">
        <el-input v-model="editForm.content" type="textarea" :rows="6" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="showEdit = false">取消</el-button>
      <el-button type="primary" @click="submitEdit" :loading="editing">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { StarFilled, Check, QuestionFilled, Edit, Delete, Medal, Select } from '@element-plus/icons-vue'
import { communityApi } from '@/api/community'
import { getErrorMessage } from '@/api/http'
import { useAuthStore } from '@/stores/auth'

const route = useRoute()
const postId = Number(route.params.id)

const loading = ref(false)
const post = ref<any>(null)
const items = ref<any[]>([])
const page = ref(1)
const pageSize = ref(20)
const total = ref(0)
const commentText = ref('')
const commenting = ref(false)
const authStore = useAuthStore()

// 初始化认证状态
const initializeAuth = async () => {
  authStore.initAuth()
  // 等待状态更新
  await new Promise(resolve => setTimeout(resolve, 200))
}
const isOwner = computed(() => !!authStore.user && post.value && authStore.user.id === post.value.userId)
const canMarkSolution = computed(() => 
  !!authStore.user && 
  post.value && 
  authStore.user.id === post.value.userId && 
  post.value.postType === 'QUESTION'
)

// 排序评论：已采纳的答案优先显示
const sortedComments = computed(() => {
  return [...items.value].sort((a, b) => {
    // 已采纳的答案排在最前面
    if (a.isSolution && !b.isSolution) return -1
    if (!a.isSolution && b.isSolution) return 1
    // 相同状态按时间排序
    return new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()
  })
})

const showEdit = ref(false)
const editForm = ref({ title: '', content: '' })
const editing = ref(false)

const loadPost = async () => {
  try {
    loading.value = true
    post.value = await communityApi.getPost(postId)
  } catch (e: any) {
    ElMessage.error(getErrorMessage(e))
  } finally {
    loading.value = false
  }
}

const loadComments = async () => {
  try {
    const res = await communityApi.getComments(postId, { page: page.value, pageSize: pageSize.value })
    items.value = res.content || []
    total.value = res.totalElements || 0
  } catch (e: any) {
    ElMessage.error(getErrorMessage(e))
  }
}

const submitComment = async () => {
  if (!commentText.value.trim()) {
    ElMessage.warning('请输入内容')
    return
  }
  try {
    commenting.value = true
    await communityApi.createComment(postId, { content: commentText.value })
    commentText.value = ''
    await loadComments()
    ElMessage.success('评论成功')
  } catch (e: any) {
    ElMessage.error(getErrorMessage(e))
  } finally {
    commenting.value = false
  }
}

const likePost = async () => {
  try {
    await communityApi.likePost(postId)
    await loadPost()
  } catch (e: any) {
    ElMessage.error(getErrorMessage(e))
  }
}

const likeComment = async (id: number) => {
  try {
    await communityApi.likeComment(id)
    await loadComments()
  } catch (e: any) {
    ElMessage.error(getErrorMessage(e))
  }
}

const markSolution = async (id: number) => {
  try {
    await communityApi.markAsSolution(id)
    await Promise.all([loadPost(), loadComments()])
    ElMessage.success('🎉 已采纳为最佳答案！问题已标记为已解决')
  } catch (e: any) {
    ElMessage.error(getErrorMessage(e))
  }
}

const openEdit = () => {
  if (!post.value) return
  showEdit.value = true
  editForm.value.title = post.value.title
  editForm.value.content = post.value.content
}

const submitEdit = async () => {
  try {
    editing.value = true
    await communityApi.updatePost(postId, { courseId: post.value.courseId, title: editForm.value.title, content: editForm.value.content, postType: post.value.postType })
    showEdit.value = false
    await loadPost()
    ElMessage.success('更新成功')
  } catch (e: any) {
    ElMessage.error(getErrorMessage(e))
  } finally {
    editing.value = false
  }
}

const removePost = async () => {
  try {
    await communityApi.deletePost(postId)
    ElMessage.success('删除成功')
    history.back()
  } catch (e: any) {
    ElMessage.error(getErrorMessage(e))
  }
}



const escapeHtml = (s: string) => s.replace(/[&<>"]/g, (ch) => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[ch] as string))
const formatTime = (s: string) => new Date(s).toLocaleString('zh-CN')

onMounted(async () => {
  await initializeAuth()
  await loadPost()
  await loadComments()
})
</script>

<style scoped>
.post-detail { max-width: 900px; margin: 0 auto; padding: 20px; }
.post-card, .comments-card { background: #fff; border: 1px solid #eee; border-radius: 8px; padding: 16px; margin-bottom: 16px; }
.post-header .title { margin: 0 0 6px 0; }
.meta { color: #909399; font-size: 12px; }
.content { white-space: pre-wrap; line-height: 1.8; margin-top: 8px; }
.actions { margin-top: 12px; display: flex; gap: 8px; align-items: center; }
.comment-editor { margin-bottom: 16px; }
.comment-item { 
  border-bottom: 1px solid #f0f0f0; 
  padding: 12px 0; 
  transition: all 0.3s ease;
}
.comment-item:last-child { border-bottom: none; }
.comment-item.best-answer { 
  background: linear-gradient(90deg, #f0f9ff 0%, #ecfdf5 100%); 
  border: 1px solid #10b981;
  border-radius: 8px;
  padding: 16px;
  margin: 8px 0;
  box-shadow: 0 2px 8px rgba(16, 185, 129, 0.1);
}
.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}
.comment-meta { color: #909399; font-size: 12px; }
.comment-actions { margin-top: 8px; display: flex; gap: 8px; align-items: center; }
.pager { margin-top: 12px; text-align: center; }
</style>




